package com.source.diyjuc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author wengqy
 * @Date 2021/1/18
 */
public class ABADemo3 {

    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            // 获得版本号
            System.out.println("T1 stamp 01=>" + stamp);
            // 暂停2秒钟，保证下面线程获得初始版本号
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = atomicStampedReference.compareAndSet(100, 101,
                    atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println(b);

            System.out.println("T1 stamp 02=>" + atomicStampedReference.getStamp());
            boolean b1 = atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(),
                    atomicStampedReference.getStamp() + 1);
            System.out.println(b1);
            System.out.println("T1 stamp 03=>" + atomicStampedReference.getStamp());
        }, "T1").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            // 获得版本号
            System.out.println("T2 stamp 01=>" + stamp);
            // 暂停3秒钟，保证上面线程先执行
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean result = atomicStampedReference.compareAndSet(100, 2019, stamp, stamp + 1);
            System.out.println("T2 是否修改成功 =>" + result);
            System.out.println("T2 最新stamp =>" + atomicStampedReference.getStamp());
            System.out.println("T2 当前的最新值 =>" + atomicStampedReference.getReference());
        }, "T2").start();
    }

}
